package com.nlecloud.bc.config;

import com.nlecloud.bc.util.FileUtil;
import com.nlecloud.bc.util.URL2SingletonHtml;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 * @author warrior
 * @description
 */
@Configuration
@Slf4j
public class PhantomjsConfig {

    @Value("${phantomjs.load_web_page}")
    private String jsPath;

    @Value("${phantomjs.bin}")
    private String customPath;

    /**
     * 用phantomjs获取渲染后的页面内容
     *
     * @param url     页面地址
     * @param imgPath 保存截图文件的地址
     * @return 页面html
     * @throws IOException
     */
    public String toHTML(String url, String imgPath) throws IOException {
        StringBuilder sb = new StringBuilder();
        Runtime runtime = Runtime.getRuntime();
        String encoding = System.getProperty("file.encoding");
        String cmd = customPath + " --output-encoding=" + encoding + " " + jsPath + " " + url + " " + imgPath;
        String chmod = "chmod +x " + customPath;
        log.info("chmod cmd:" + chmod);
        runtime.exec(chmod);
        log.info("cmd:" + cmd);
        Process process = runtime.exec(cmd);
        InputStream is = process.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        return sb.toString();
    }

    /**
     * url指定页面转化为单个html文件，并截图
     *
     * @param url      指定页面的url
     * @param htmlPath html文件的保存路径
     * @param imgPath  截图文件的保存路径
     * @throws IOException
     */
    public void URL2HtmlAndImg(String url, String htmlPath, String imgPath) throws Exception {
        log.info("begin url to html and image ......");
        toHTML(url, imgPath);
        String html = FileUtil.getHtmlFromUrl(url);
        HashMap<String, String> urlMap = URL2SingletonHtml.compile(html);
        URL2SingletonHtml.saveAsFileWriter(URL2SingletonHtml.replaceHtml(html, urlMap), htmlPath);
        log.info("end url to html and image ......");
    }
}
